import re
from datetime import datetime
from datetime import timedelta
from django.conf import settings
from django.http import HttpResponseForbidden, JsonResponse
from django_redis import get_redis_connection
from rest_framework import status, mixins
from django.contrib.auth import get_user_model
from rest_framework.generics import RetrieveUpdateAPIView, GenericAPIView, CreateAPIView
from rest_framework.mixins import UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet, ModelViewSet

from apps.questions.models import Label
from apps.users.models import User
from apps.users.serializers import PersonSerializer, RegisterSerializer, UploadSerializer, UserLikeSerializer

from tensquare.settings.dev import REGEX_MOBILE
from rest_framework import mixins
# User = get_user_model()


# 短信验证码
class SmsView(APIView):
    def get(self, request, mobile):
        from random import randint
        sms_code = "%06d" % randint(0, 999999)
        # sms_code = randint(100000, 999999)
        print(sms_code)
        sms_redis_client = get_redis_connection('verify')

        # 1.取出标识
        send_flag = sms_redis_client.get('send_flag_%s' % mobile)
        # 2.判断标识
        if send_flag:
            return Response({'message': '短信发送频繁'}, status=status.HTTP_403_FORBIDDEN)

        # 1.实例化管道
        pipeline = sms_redis_client.pipeline()
        # 2.将任务添加管道
        pipeline.setex('send_flag_%s' % mobile, 60, 1)
        pipeline.setex("sms_%s" % mobile, 300, sms_code)
        # 3.实行管道'
        pipeline.execute()

        # 4.让第三方 容联云-给手机号-发送短信
        # from celery_tasks.sms.tasks import ccp_send_sms_code
        # ccp_send_sms_code.delay(mobile, sms_code)

        # 5.告诉前端短信发送完毕
        return Response({'success': True, 'sms_code': sms_code, 'message': 'OK'})

# 注册
class RegisterView(GenericAPIView):
    serializer_class = RegisterSerializer

    def post(self,request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 反序列化-数据保存(save内部会调用序列化器类的create方法)
        serializer.save()


        return Response(serializer.data, status=status.HTTP_201_CREATED)

class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = PersonSerializer

    def retrieve(self, request, *args, **kwargs):
        serializer = self.serializer_class(request.user)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        serializer = self.serializer_class(request.user, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

class PassWord(APIView):

    def put(self, request):
        # 获取参数
        password = request.data["password"]
        # 获得请求用户
        user = User.objects.get(id=request.user.id)
        if len(password) > 20 or len(password) < 8:
            # raise Exception("密码长度需要8到20位")
            return Response({'message': '密码长度需要8～20位'}, status=status.HTTP_403_FORBIDDEN)
        # 修改密码为新密码
        user.set_password(password)
        user.save()
        # 返回数据
        return Response(status=status.HTTP_202_ACCEPTED)


class UserLike(APIView):

    def post(self,request,pk):
        auther = User.objects.get(id=pk)
        user = request.user
        all_user = auther.fans.all()

        if user not in all_user:
            auther.fans.add(request.user)
            data = {
                'message':'关注成功',
                'success': True
            }
            return Response(data)
        else:
            data = {
                'message':'关注失败',
                'success':False
            }
            return Response(data)

    def delete(self,request,pk):

        auther = User.objects.get(id=pk)
        user = request.user
        fans = auther.fans.all()
        if user in fans:
            auther.fans.remove(user)
            return Response({
                'success': True,
                'message': '取消关注'
            })
        else:
            return Response({
                'success': False,
                'message': '取消关注失败'
            })

class UserLable(APIView):
    def put(self, request):
        labels_now = request.data.get('labels')
        user = request.user
        if not user.is_authenticated:
            return Response({'message': '请登录'}, status=status.HTTP_401_UNAUTHORIZED)

        labels = user.labels.all()

        for labels in labels:
            user.labels.remove(labels)

        for pk in labels_now:
            try:
                label = Label.objects.get(id=pk)
                user.labels.add(label)
            except:
                return Response({'message': '无效标签'}, status=status.HTTP_404_NOT_FOUND)

        return Response({'message': '修改成功', 'success': True})


from apps.users.serializers import LoginSerializer

class Login(CreateAPIView):

    queryset = User
    serializer_class = LoginSerializer

    # def post(self, request):
    #     data = request.data
    #
    #     serializer = self.get_serializer(data=data)
    #     if serializer.is_valid():
    #         serializer.save()
    #         return Response(serializer.data)
    #     return Response(serializer.errors)


















